<template>
  <baidu-map class="map" ref="bmap"
             :center="mapCenter" 
             :zoom="mapZoom"
             :scroll-wheel-zoom="true"
             :dragging="mapDragging"
             :auto-resize="true"
             @ready="handleMapReady"
             @moving="syncCenterAndZoom"
             @moveend="syncCenterAndZoom"
             @zoomend="syncCenterAndZoom">
    
    <!-- 控制按钮区域 -->
    <div class="map-controls">
      <el-button 
        class="toggle-controls-btn"
        @click="showControls = !showControls"
        :icon="showControls ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
        circle
      ></el-button>

      <div v-show="showControls">
        <el-row :gutter="10">
          <el-col :span="3" v-for="location in firstRowLocations" :key="location.name">
            <el-button @click="showLocation(location)" type="primary" class="control-btn">
              {{ location.name }}
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="3" v-for="location in secondRowLocations" :key="location.name + '-cable'">
            <el-button @click="startAddCable(location.name)" type="success" class="control-btn">
              添加光缆
            </el-button>
            <el-button @click="editCompanyCable(location.name)" type="warning" class="control-btn">
              修改光缆
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-button 
              @click="showAllCables" 
              type="info" 
              class="control-btn"
              v-if="currentCompany">
              显示全部光缆
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-box">
      <el-autocomplete
        v-model="searchKeyword"
        :fetch-suggestions="querySearch"
        placeholder="请输入光缆或炮筒名称"
        @select="handleSelect"
        size="small"
        style="width: 100%"
      >
        <el-button slot="append" icon="el-icon-search" @click="searchLocation"></el-button>
      </el-autocomplete>
      <el-button 
        v-show="searchKeyword"
        @click="resetHighlight"
        icon="el-icon-refresh"
        circle
        size="mini"
        style="position: absolute; right: -30px; top: 10px;"
      ></el-button>
    </div>

    <bm-navigation :anchor="anchorPosition" />

    <!-- 光缆编辑对话框 -->
    <el-dialog :title="cableDialogTitle" :visible.sync="showCableDialog" width="600px">
      <el-form :model="cableForm" :rules="cableRules" ref="cableForm" label-width="100px">
        <el-form-item label="光缆名称" prop="name">
          <el-input v-model="cableForm.name" placeholder="请输入光缆名称"></el-input>
        </el-form-item>
        <el-form-item label="所属支公司" prop="company">
          <el-select v-model="cableForm.company" placeholder="请选择所属支公司" style="width:100%">
            <el-option
              v-for="dict in dict.type.sys_dept_dept_name"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="光缆类型" prop="type">
          <el-select v-model="cableForm.type" placeholder="请选择光缆类型" style="width:100%">
            <el-option
              v-for="item in cableTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="光缆状态" prop="status">
          <el-select v-model="cableForm.status" placeholder="请选择光缆状态" style="width:100%">
            <el-option
              v-for="item in cableStatuses"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelAddCable">取 消</el-button>
        <el-button type="primary" @click="validateCableForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 炮筒编辑对话框 -->
    <el-dialog :title="manholeDialogTitle" :visible.sync="showManholeDialog" width="800px">
      <el-alert
        v-if="isPositionUpdated"
        title="炮筒位置已更新，请确认信息后保存"
        type="warning"
        show-icon
        style="margin-bottom: 20px;"
      />
      <el-form :model="manholeForm" :rules="manholeRules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="炮筒名称" prop="name">
              <el-input v-model="manholeForm.name" placeholder="请输入炮筒名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属光缆ID" prop="cableId">
              <el-input v-model="manholeForm.cableId" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="manholeForm.longitude" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="manholeForm.latitude" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="顺序号" prop="sequence">
              <el-input-number v-model="manholeForm.sequence" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="与上一点距离(km)" prop="height">
              <el-input v-model="manholeForm.height" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="炮筒类型" prop="type">
              <el-select v-model="manholeForm.type" placeholder="请选择炮筒类型">
                <el-option
                  v-for="item in manholeTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="炮筒状态" prop="status">
              <el-select v-model="manholeForm.status" placeholder="请选择炮筒状态">
                <el-option
                  v-for="item in manholeStatuses"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelAddManhole">取 消</el-button>
        <el-button type="primary" @click="saveManhole">确 定</el-button>
      </div>
    </el-dialog>
  </baidu-map>
</template>

<script>
import { listManholes, addManholes, updateManholes } from "@/api/system/manholes";
import { listCables, addCables, updateCables, getCables } from "@/api/system/cables";

export default {
  name: "CableMap",
  dicts: ['sys_dept_dept_name'],
  data() {
    return {
      // 地图基础设置
      mapCenter: { lng: 113.146, lat: 23.046 },
      mapZoom: 15,
      mapDragging: true,
      anchorPosition: 'BMAP_ANCHOR_TOP_RIGHT',
      
      // 地图实例
      map: null,
      BMap: null,
      localSearch: null,
      
      // 数据列表
      manholesList: [],
      cablesList: [],
      cableMap: {},
      
      // 搜索相关
      searchKeyword: '',
      
      // 对话框控制
      showCableDialog: false,
      showManholeDialog: false,
      
      // 表单数据
      cableForm: {
        id: null,
        name: '', // 初始为空
        company: '',
        type: '64芯',
        status: '在用',
        length: 0,
        startPoint: null,
        endPoint: null
      },
      manholeForm: {
        id: null,
        name: '',
        longitude: null,
        latitude: null,
        cableId: null,
        sequence: 1,
        height: null,
        type: '地下',
        status: '正常'
      },
      
      // 验证规则
      cableRules: {
        name: [
          { required: true, message: '请输入光缆名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '请选择所属支公司', trigger: 'change' }
        ]
      },
      manholeRules: {
        name: [{ required: true, message: '请输入炮筒名称', trigger: 'blur' }],
        sequence: [{ required: true, message: '请输入顺序号', trigger: 'blur' }]
      },
      
      // 选项数据
      cableTypes: [
        { value: '12芯', label: '12芯' },
        { value: '48芯', label: '48芯' },
        { value: '64芯', label: '64芯' }
      ],
      cableStatuses: [
        { value: '在用', label: '在用' },
        { value: '停用', label: '停用' },
        { value: '待用', label: '待用' }
      ],
      manholeTypes: [
        { value: '地下', label: '地下' },
        { value: '架空', label: '架空' }
      ],
      manholeStatuses: [
        { value: '正常', label: '正常' },
        { value: '待维修', label: '待维修' },
        { value: '停用', label: '停用' }
      ],
      
      // 位置数据
      locations: [
        { name: '南海中心机房', lng: 113.146157, lat: 23.046162, zoom: 15 },
        { name: '桂城区域运营中心', lng: 113.202611, lat: 23.040284, zoom: 19 },
        { name: '狮山区域运营中心', lng: 112.98566, lat: 23.097611, zoom: 15 },
        { name: '大沥支公司', lng: 113.131625, lat: 23.119427, zoom: 15 },
        { name: '里水支公司', lng: 113.171871, lat: 23.203495, zoom: 15 },
        { name: '九江支公司', lng: 113.025065, lat: 22.840208, zoom: 15 },
        { name: '丹灶支公司', lng: 112.926487, lat: 23.046573, zoom: 15 },
        { name: '西樵支公司', lng: 112.972828, lat: 22.955164, zoom: 15 }
      ],
      firstRowLocations: [],
      secondRowLocations: [],
      
      // 光缆绘制状态
      isAddingCable: false,
      cablePoints: [],
      currentCableId: null,
      showControls: true,
      isPositionUpdated: false,
      currentCompany: null,
    };
  },
  computed: {
    cableDialogTitle() {
      return this.cableForm.id ? '修改光缆' : '添加光缆';
    },
    manholeDialogTitle() {
      return this.manholeForm.id ? '修改炮筒' : '添加炮筒';
    },
    companyCables() {
      return this.cablesList.reduce((acc, cable) => {
        if (!acc[cable.company]) acc[cable.company] = [];
        acc[cable.company].push(cable);
        return acc;
      }, {});
    }
  },
  created() {
    this.splitLocations();
    this.loadData();
  },
  methods: {
    // 辅助方法
    splitLocations() {
      this.firstRowLocations = this.locations.slice(0, Math.ceil(this.locations.length));
      this.secondRowLocations = this.locations.slice(0, Math.ceil(this.locations.length));
    },
    
    findManholeById(id) {
      return this.manholesList.find(m => m.id === id);
    },
    
    getSortedManholesByCableId(cableId) {
      return this.manholesList
        .filter(m => m.cableId === cableId)
        .sort((a, b) => a.sequence - b.sequence);
    },
    
    groupManholesByCableId() {
      return this.manholesList.reduce((acc, manhole) => {
        if (!acc[manhole.cableId]) acc[manhole.cableId] = [];
        acc[manhole.cableId].push(manhole);
        return acc;
      }, {});
    },
    
    handleError(message, error) {
      console.error(`${message}:`, error);
      this.$message.error(message);
    },
    
    // 地图方法
    clearMapOverlays(keepControls = false) {
      if (!this.map) return;
      
      // 获取所有覆盖物
      const overlays = this.map.getOverlays();
      
      // 移除覆盖物（可选保留控制元素）
      overlays.forEach(overlay => {
        if (keepControls) {
          // 保留搜索框和控制按钮等UI元素
          const isControl = overlay instanceof BMap.Control || 
                          overlay.getContainer?.()?.classList?.contains('map-controls') ||
                          overlay.getContainer?.()?.classList?.contains('search-box');
          if (!isControl) {
            this.map.removeOverlay(overlay);
          }
        } else {
          this.map.removeOverlay(overlay);
        }
      });
    },
    
    createCablePolyline(points, color) {
      const polyline = new this.BMap.Polyline(points, {
        strokeWeight: 6,
        strokeColor: color,
        strokeOpacity: 0.8
      });
      this.map.addOverlay(polyline);
      return polyline;
    },
    
    setupCableInfoWindow(polyline, cableId, point) {
      const cableName = this.cableMap[cableId] || '未知光缆';
      const content = `<div>光缆名称: ${cableName}</div><div>光缆ID: ${cableId}</div>`;
      const infoWindow = new this.BMap.InfoWindow(content, { title: "光缆信息" });
      
      polyline.addEventListener('click', () => {
        this.map.openInfoWindow(infoWindow, point);
      });
    },
    
    createManholeMarker(manhole) {
      const point = new this.BMap.Point(manhole.longitude, manhole.latitude);
      const marker = new this.BMap.Marker(point);
      
      marker.enableDragging();
      marker.addEventListener("dragend", (e) => {
        this.updateManholePosition(manhole.id, e.point.lng, e.point.lat);
      });
      
      const infoWindow = new this.BMap.InfoWindow(
        `<div>名称: ${manhole.name}</div>
         <div>类型: ${manhole.type}</div>
         <div>状态: ${manhole.status}</div>`,
        { title: "炮筒信息" }
      );
      
      marker.addEventListener("click", () => {
        this.map.openInfoWindow(infoWindow, point);
      });
      
      this.map.addOverlay(marker);
    },
    
    // 数据加载
    async loadData() {
      try {
        const [manholesRes, cablesRes] = await Promise.all([
          listManholes({ pageNum: 1, pageSize: 1000 }),
          listCables({ pageNum: 1, pageSize: 1000 })
        ]);
        
        this.manholesList = manholesRes.rows;
        this.cablesList = cablesRes.rows;
        this.cableMap = cablesRes.rows.reduce((map, cable) => {
          map[cable.id] = cable.name;
          return map;
        }, {});
        
        if (this.map) {
          this.currentCompany ? this.showCurrentCompanyCables() : this.drawAllCables();
        }
      } catch (error) {
        this.handleError('加载数据失败', error);
      }
    },
    
    // 地图操作
    handleMapReady({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
      this.mapCenter = { lng: 113.146, lat: 23.046 };
      this.mapZoom = 15;
      map.enableScrollWheelZoom(true);
      
      this.localSearch = new BMap.LocalSearch(map, {
        renderOptions: { map: map }
      });
      
      map.addEventListener("click", this.handleMapClick);
      
      if (this.manholesList.length > 0) {
        this.drawAllCables();
      }
    },
    
    handleMapClick(e) {
      if (!this.isAddingCable) return;
      
      const point = e.point;
      this.cablePoints.push(point);
      this.addMarker(point);
      
      if (this.cablePoints.length > 1) {
        this.drawTempPolyline();
      }
      
      this.openManholeForm(point.lng, point.lat);
    },

    querySearch(queryString, cb) {
      const results = [];
      
      // 搜索光缆
      this.cablesList.forEach(cable => {
        if (cable.name.includes(queryString)) {
          results.push({
            value: `${cable.name} (光缆)`,  // 添加类型标识
            id: cable.id,
            type: 'cable'
          });
        }
      });
      
      // 搜索炮筒
      this.manholesList.forEach(manhole => {
        if (manhole.name.includes(queryString)) {
          results.push({
            value: `${manhole.name} (炮筒)`,  // 添加类型标识
            id: manhole.id,
            type: 'manhole'
          });
        }
      });
      
      cb(results);
    },

    handleSelect(item) {
      if (item.type === 'cable') {
        this.highlightCable(item.id);
      } else {
        this.highlightManhole(item.id);
      }
    },
    
    addMarker(point) {
      const marker = new this.BMap.Marker(point);
      this.map.addOverlay(marker);
    },
    
    drawTempPolyline() {
      const points = this.cablePoints.map(p => new this.BMap.Point(p.lng, p.lat));
      const polyline = new this.BMap.Polyline(points, {
        strokeWeight: 4,
        strokeColor: '#1890ff',
        strokeOpacity: 0.6
      });
      this.map.addOverlay(polyline);
    },
    
    drawAllCables() {
      // 清除现有覆盖物但保留控制按钮
      this.clearMapOverlays(true);

      const groupedManholes = this.groupManholesByCableId();
      const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];

      Object.entries(groupedManholes).forEach(([cableId, manholes], index) => {
        const sortedManholes = manholes.sort((a, b) => a.sequence - b.sequence);
        const points = sortedManholes.map(m => new this.BMap.Point(m.longitude, m.latitude));

        const polyline = this.createCablePolyline(points, colors[index % colors.length]);
        this.setupCableInfoWindow(polyline, cableId, points[0]);
        sortedManholes.forEach(manhole => this.createManholeMarker(manhole));
      });

      // 添加所有支公司位置标记
      this.locations.forEach(location => {
        const point = new this.BMap.Point(location.lng, location.lat);
        const marker = new this.BMap.Marker(point, {
          enableDragging: false
        });

        // 自定义标记样式
        marker.addEventListener("load", () => {
          const icon = marker.getIcon();
          if (icon) {
            const div = icon.getElementsByTagName("div")[0];
            if (div) {
              div.style.border = "3px solid #1890ff";
              div.style.borderRadius = "50%";
            }
          }
        });

        const infoWindow = new this.BMap.InfoWindow(
          `<div style="font-weight:bold">${location.name}</div>
          <div>位置: ${location.lng.toFixed(6)}, ${location.lat.toFixed(6)}</div>`,
          { title: "支公司位置", width: 200 }
        );

        marker.addEventListener("click", () => {
          this.map.openInfoWindow(infoWindow, point);
        });

        this.map.addOverlay(marker);

        // 添加公司名称标签
        const label = new this.BMap.Label(location.name, {
          offset: new this.BMap.Size(20, -10) // 调整标签位置
        });
        label.setStyle({
          color: '#1890ff',
          fontSize: '14px',
          height: '35px',
          lineHeight: '20px',
          fontFamily: 'Arial',
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          border: '1px solid #1890ff',
          borderRadius: '5px',
          padding: '5px',
          whiteSpace: 'nowrap'
        });
        label.setPosition(point);
        this.map.addOverlay(label);
      });
    },
    
    showCurrentCompanyCables() {
      if (!this.currentCompany) return;

      // 清除现有覆盖物但保留控制按钮
      this.clearMapOverlays(true);

      const companyCables = this.cablesList.filter(c => c.company === this.currentCompany);
      if (companyCables.length === 0) {
        this.$message.warning('该支公司没有光缆数据');
        return;
      }

      const manholes = this.manholesList.filter(m => 
        companyCables.some(c => c.id === m.cableId)
      );

      // 绘制光缆和炮筒
      const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];
      companyCables.forEach((cable, index) => {
        const cableManholes = manholes
          .filter(m => m.cableId === cable.id)
          .sort((a, b) => a.sequence - b.sequence);

        if (cableManholes.length === 0) return;

        const points = cableManholes.map(m => new this.BMap.Point(m.longitude, m.latitude));
        const polyline = this.createCablePolyline(points, colors[index % colors.length]);

        polyline.addEventListener('click', () => {
          const content = `
            <div>光缆名称: ${cable.name}</div>
            <div>光缆类型: ${cable.type}</div>
            <div>光缆状态: ${cable.status}</div>
          `;
          const infoWindow = new this.BMap.InfoWindow(content, { title: "光缆信息" });
          this.map.openInfoWindow(infoWindow, points[0]);
        });

        cableManholes.forEach(manhole => this.createManholeMarker(manhole));
      });

      // 添加支公司位置标记
      const companyLocation = this.locations.find(loc => 
        this.dict.type.sys_dept_dept_name.some(d => d.label === loc.name && d.value === this.currentCompany)
      );

      if (companyLocation) {
        const point = new this.BMap.Point(companyLocation.lng, companyLocation.lat);
        const marker = new this.BMap.Marker(point, {
          enableDragging: false
        });

        // 自定义标记样式
        marker.addEventListener("load", () => {
          const icon = marker.getIcon();
          if (icon) {
            const div = icon.getElementsByTagName("div")[0];
            if (div) {
              div.style.border = "3px solid #1890ff";
              div.style.borderRadius = "50%";
            }
          }
        });

        const infoWindow = new this.BMap.InfoWindow(
          `<div style="font-weight:bold">${companyLocation.name}</div>
          <div>位置: ${companyLocation.lng.toFixed(6)}, ${companyLocation.lat.toFixed(6)}</div>`,
          { title: "支公司位置", width: 200 }
        );

        marker.addEventListener("click", () => {
          this.map.openInfoWindow(infoWindow, point);
        });

        this.map.addOverlay(marker);

        // 添加公司名称标签
        const label = new this.BMap.Label(companyLocation.name, {
          offset: new this.BMap.Size(20, -10) // 调整标签位置
        });
        label.setStyle({
          color: '#1890ff',
          fontSize: '14px',
          height: '35px',
          lineHeight: '20px',
          fontFamily: 'Arial',
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          border: '1px solid #1890ff',
          borderRadius: '5px',
          padding: '5px',
          whiteSpace: 'nowrap'
        });
        label.setPosition(point);
        this.map.addOverlay(label);
      }
    },
    
    // 计算相关
    calculateDistance(lng1, lat1, lng2, lat2) {
      const R = 6371; // 地球半径(km)
      const dLat = this.deg2rad(lat2 - lat1);
      const dLng = this.deg2rad(lng2 - lng1);
      
      const a =
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
        Math.sin(dLng/2) * Math.sin(dLng/2);
        
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      return R * c;
    },
    
    deg2rad(deg) {
      return deg * (Math.PI/180);
    },
    
    calculateCableLength(cableId) {
      const manholes = this.getSortedManholesByCableId(cableId);
      

      if (manholes.length < 2) return "0.00";
      
      return manholes.reduce((total, current, index, array) => {
        if (index === 0) return total;
        const prev = array[index - 1];
        return total + this.calculateDistance(
          prev.longitude, prev.latitude,
          current.longitude, current.latitude
        );
      }, 0).toFixed(2);
    },
    
    calculateManholeHeight(manhole) {
      const cableManholes = this.getSortedManholesByCableId(manhole.cableId);
      const index = cableManholes.findIndex(m => m.id === manhole.id);
      
      if (index <= 0) return null;
      
      const prevManhole = cableManholes[index - 1];
      return this.calculateDistance(
        prevManhole.longitude, prevManhole.latitude,
        manhole.longitude, manhole.latitude
      ).toFixed(2);
    },
    
    calculateDistanceToLastPoint() {
      if (this.cablePoints.length < 2) return null;
      
      const last = this.cablePoints[this.cablePoints.length - 2];
      const current = this.cablePoints[this.cablePoints.length - 1];
      
      return this.calculateDistance(
        last.lng, last.lat,
        current.lng, current.lat
      ).toFixed(2);
    },
    
    // 表单操作
    openManholeForm(lng, lat) {
      this.manholeForm = {
        id: null,
        name: `炮筒-${this.cablePoints.length}`,
        longitude: lng,
        latitude: lat,
        cableId: this.currentCableId,
        sequence: this.cablePoints.length,
        height: this.calculateDistanceToLastPoint(),
        type: '地下',
        status: '正常'
      };
      
      this.showManholeDialog = true;
    },
    
    async updateManholePosition(manholeId, lng, lat) {
      try {
        const manhole = this.findManholeById(manholeId);
        if (!manhole) return;
        
        this.isPositionUpdated = true;
        Object.assign(manhole, { longitude: lng, latitude: lat });
        
        this.manholeForm = {
          ...manhole,
          height: this.calculateManholeHeight(manhole)
        };
        
        this.showManholeDialog = true;
      } catch (error) {
        this.handleError('更新炮筒位置失败', error);
      }
    },
    
    async updateAdjacentManholes(updatedManhole) {
      const cableManholes = this.getSortedManholesByCableId(updatedManhole.cableId);
      const index = cableManholes.findIndex(m => m.id === updatedManhole.id);
      
      if (index > 0) {
        const prevManhole = cableManholes[index - 1];
        prevManhole.height = this.calculateDistance(
          prevManhole.longitude, prevManhole.latitude,
          updatedManhole.longitude, updatedManhole.latitude
        ).toFixed(2);
        await updateManholes(prevManhole);
      }
      
      if (index < cableManholes.length - 1) {
        const nextManhole = cableManholes[index + 1];
        nextManhole.height = this.calculateDistance(
          updatedManhole.longitude, updatedManhole.latitude,
          nextManhole.longitude, nextManhole.latitude
        ).toFixed(2);
        await updateManholes(nextManhole);
      }
    },
    
async updateCableInfo(cableId) {
  try {
    const cableRes = await getCables(cableId);
    const cable = cableRes.data;
    const manholes = this.getSortedManholesByCableId(cableId);
    
    cable.length = this.calculateCableLength(cableId);
    
    if (manholes.length > 0) {
      cable.startPoint = manholes[0].name;
      cable.endPoint = manholes[manholes.length - 1].name;
      cable.startPointName = manholes[0].name;
      cable.endPointName = manholes[manholes.length - 1].name;
    }
    
    await updateCables(cable);
  } catch (error) {
    this.handleError('更新光缆信息失败', error);
    throw error;
  }
},
    
    // 业务操作
    startAddCable(companyName) {
      const company = this.dict.type.sys_dept_dept_name.find(d => d.label === companyName);
      if (!company) {
        this.$message.warning('未找到对应的支公司');
        return;
      }
      
      this.isAddingCable = true;
      this.cablePoints = [];
      this.currentCableId = this.generateCableId();
      this.cableForm = {
        id: null,
        name: '', // 初始为空
        company: company.value,
        type: '64芯',
        status: '在用',
        length: 0,
        startPoint: null,
        endPoint: null
      };
      
      this.$message.info(`请在地图上点击绘制${companyName}的光缆路径`);
      this.showCableDialog = true;
      
      // 重置验证状态
      this.$nextTick(() => {
        if (this.$refs.cableForm) {
          this.$refs.cableForm.clearValidate();
        }
      });
    },
    
    validateCableForm() {
      this.$refs.cableForm.validate(valid => {
        if (valid) {
          this.saveCable();
        } else {
          this.$message.warning('请填写完整的光缆信息');
          return false;
        }
      });
    },
    
    generateCableId() {
      const maxId = this.cablesList.reduce((max, cable) => 
        Math.max(max, parseInt(cable.id)), 0);
      return (maxId + 1).toString();
    },
    
    async saveCable() {
      try {
        const cableManholes = this.getSortedManholesByCableId(this.currentCableId);
        
        this.cableForm = {
          ...this.cableForm,
          length: this.calculateCableLength(this.currentCableId),
          ...(cableManholes.length > 0 ? {
            startPoint: cableManholes[0].name,
            endPoint: cableManholes[cableManholes.length - 1].name,
            startPointName: cableManholes[0].name,
            endPointName: cableManholes[cableManholes.length - 1].name
          } : {})
        };
        
        
        const action = this.cableForm.id ? updateCables : addCables;
        const res = await action(this.cableForm);
        
        if (!this.cableForm.id) {
          this.currentCableId = res.data.id;
        }
        
        this.$message.success(`${this.cableForm.id ? '修改' : '添加'}光缆成功`);
        this.showCableDialog = false;
        await this.refreshData();
      } catch (error) {
        this.handleError('保存光缆失败', error);
      }
    },
    
async saveManhole() {
  try {
    if (this.manholeForm.id) {
      const originalManhole = this.findManholeById(this.manholeForm.id);
      if (originalManhole && 
          (originalManhole.longitude !== this.manholeForm.longitude || 
           originalManhole.latitude !== this.manholeForm.latitude)) {
        await this.updateAdjacentManholes(this.manholeForm);
      }
    }
    
    const action = this.manholeForm.id ? updateManholes : addManholes;
    const response = await action(this.manholeForm);

    // Update manholesList reactively
    if (this.manholeForm.id) {
      const index = this.manholesList.findIndex(m => m.id === this.manholeForm.id);
      if (index !== -1) {
        this.$set(this.manholesList, index, this.manholeForm);
      }
    } else {
      this.manholesList = [...this.manholesList, this.manholeForm];
    }

    this.$message.success(`${this.manholeForm.id ? '修改' : '添加'}炮筒成功`);
    
    if (this.manholeForm.cableId) {
      await this.updateCableInfo(this.manholeForm.cableId);
    }
    
    this.showManholeDialog = false;
    this.isPositionUpdated = false;
    await this.refreshData();
  } catch (error) {
    this.handleError('保存炮筒失败', error);
  }
},
    
    async refreshData() {
      await this.loadData();
      if (this.currentCompany) {
        this.showCurrentCompanyCables();
      }
    },
    
    editCompanyCable(companyName) {
      const company = this.dict.type.sys_dept_dept_name.find(d => d.label === companyName);
      if (!company) {
        this.$message.warning('未找到对应的支公司');
        return;
      }
      
      this.currentCompany = company.value;
      this.showCurrentCompanyCables();
    },
    
    showAllCables() {
      this.currentCompany = null;
      this.drawAllCables();
    },
    
    showLocation(location) {
      // 清除现有覆盖物但保留控制按钮
      this.clearMapOverlays(true); // 传入true表示保留控制元素
      
      // 创建中心点
      const point = new this.BMap.Point(location.lng, location.lat);
      
      // 移动到该位置
      this.map.panTo(point);
      this.map.setZoom(location.zoom);
      
      // 添加支公司定位标记
      const marker = new this.BMap.Marker(point, {
        enableDragging: false // 不可拖动
      });
      
      // 自定义标记样式（使用默认图标但添加蓝色边框）
      marker.addEventListener("load", () => {
        const icon = marker.getIcon();
        if (icon) {
          const div = icon.getElementsByTagName("div")[0];
          if (div) {
            div.style.border = "3px solid #1890ff";
            div.style.borderRadius = "50%";
          }
        }
      });
      
      // 信息窗口内容
      const infoWindow = new this.BMap.InfoWindow(
        `<div style="font-weight:bold">${location.name}</div>
        <div>位置: ${location.lng.toFixed(6)}, ${location.lat.toFixed(6)}</div>`,
        { title: "支公司位置", width: 200 }
      );
      
      // 点击标记显示信息窗口
      marker.addEventListener("click", () => {
        this.map.openInfoWindow(infoWindow, point);
      });
      
      // 添加标记到地图
      this.map.addOverlay(marker);
      
      // 显示该支公司的光缆（如果存在）
      const company = this.dict.type.sys_dept_dept_name.find(d => d.label === location.name);
      if (company) {
        this.currentCompany = company.value;
        this.showCurrentCompanyCables();
      }
    },
    
    searchLocation() {
      if (!this.searchKeyword.trim()) {
        this.$message.warning('请输入搜索关键词');
        return;
      }

      // 优先搜索光缆
      const foundCable = this.cablesList.find(cable => 
        cable.name.includes(this.searchKeyword)
      );
      
      if (foundCable) {
        this.highlightCable(foundCable.id);
        return;
      }

      // 如果没有找到光缆，搜索炮筒
      const foundManhole = this.manholesList.find(manhole => 
        manhole.name.includes(this.searchKeyword)
      );
      
      if (foundManhole) {
        this.highlightManhole(foundManhole.id);
        return;
      }

      this.$message.warning('未找到匹配的光缆或炮筒');
    },

    // 高亮显示光缆（使用默认图标）
    highlightCable(cableId) {
      this.clearMapOverlays();
      
      const cableManholes = this.getSortedManholesByCableId(cableId);
      
      if (cableManholes.length === 0) {
        this.$message.warning('该光缆没有炮筒数据');
        return;
      }

      // 计算中心点
      const centerLng = cableManholes.reduce((sum, m) => sum + m.longitude, 0) / cableManholes.length;
      const centerLat = cableManholes.reduce((sum, m) => sum + m.latitude, 0) / cableManholes.length;
      
      // 移动到中心点
      this.map.panTo(new this.BMap.Point(centerLng, centerLat));
      this.map.setZoom(17);

      // 绘制高亮光缆（红色加粗）
      const points = cableManholes.map(m => new this.BMap.Point(m.longitude, m.latitude));
      const polyline = new this.BMap.Polyline(points, {
        strokeWeight: 8,  // 加粗线条
        strokeColor: '#FF0000',  // 红色
        strokeOpacity: 0.9
      });
      this.map.addOverlay(polyline);

      // 绘制炮筒（使用默认标记但添加红色边框）
      cableManholes.forEach(manhole => {
        const point = new this.BMap.Point(manhole.longitude, manhole.latitude);
        const marker = new this.BMap.Marker(point);
        
        // 添加红色边框效果
        marker.addEventListener("load", () => {
          const icon = marker.getIcon();
          if (icon) {
            const div = icon.getElementsByTagName("div")[0];
            if (div) {
              div.style.border = "3px solid red";
              div.style.borderRadius = "50%";
            }
          }
        });
        
        const infoWindow = new this.BMap.InfoWindow(
          `<div>炮筒名称: ${manhole.name}</div>
          <div>所属光缆: ${this.cableMap[manhole.cableId]}</div>
          <div>位置: ${manhole.longitude.toFixed(6)}, ${manhole.latitude.toFixed(6)}</div>`,
          { title: "炮筒信息", width: 250 }
        );
        
        marker.addEventListener("click", () => {
          this.map.openInfoWindow(infoWindow, point);
        });
        
        this.map.addOverlay(marker);
      });

      this.$message.success(`已高亮显示光缆: ${this.cableMap[cableId]}`);
    },

    // 高亮显示单个炮筒（使用默认图标）
    highlightManhole(manholeId) {
      this.clearMapOverlays();
      
      const manhole = this.findManholeById(manholeId);
      if (!manhole) return;

      // 移动到炮筒位置
      const point = new this.BMap.Point(manhole.longitude, manhole.latitude);
      this.map.panTo(point);
      this.map.setZoom(19);

      // 绘制高亮炮筒（默认标记+红色边框）
      const marker = new this.BMap.Marker(point);
      
      // 添加红色边框效果
      marker.addEventListener("load", () => {
        const icon = marker.getIcon();
        if (icon) {
          const div = icon.getElementsByTagName("div")[0];
          if (div) {
            div.style.border = "3px solid red";
            div.style.borderRadius = "50%";
            div.style.boxShadow = "0 0 10px red"; // 添加发光效果
          }
        }
      });
      
      const infoWindow = new this.BMap.InfoWindow(
        `<div>炮筒名称: ${manhole.name}</div>
        <div>所属光缆: ${this.cableMap[manhole.cableId]}</div>
        <div>位置: ${manhole.longitude.toFixed(6)}, ${manhole.latitude.toFixed(6)}</div>`,
        { title: "炮筒信息", width: 250 }
      );
      
      marker.addEventListener("click", () => {
        this.map.openInfoWindow(infoWindow, point);
      });
      
      this.map.addOverlay(marker);

      // 绘制连接的光缆（红色加粗）
      const cableManholes = this.getSortedManholesByCableId(manhole.cableId);
      if (cableManholes.length > 1) {
        const points = cableManholes.map(m => new this.BMap.Point(m.longitude, m.latitude));
        const polyline = new this.BMap.Polyline(points, {
          strokeWeight: 6,
          strokeColor: '#FF0000',
          strokeOpacity: 0.7
        });
        this.map.addOverlay(polyline);
      }

      this.$message.success(`已高亮显示炮筒: ${manhole.name}`);
    },
    // 高亮显示单个炮筒
    highlightManhole(manholeId) {
  this.clearMapOverlays();
  
  const manhole = this.findManholeById(manholeId);
  if (!manhole) return;

  // 移动到炮筒位置
  const point = new this.BMap.Point(manhole.longitude, manhole.latitude);
  this.map.panTo(point);
  this.map.setZoom(19); // 最大缩放级别

  // 绘制高亮炮筒
  const icon = new this.BMap.Icon(
    require('@/assets/images/mapred.png'), // 高亮图标
    new this.BMap.Size(40, 40),
    { anchor: new this.BMap.Size(20, 20) }
  );
  const marker = new this.BMap.Marker(point, { icon });
  
  const infoWindow = new this.BMap.InfoWindow(
    `<div>炮筒名称: ${manhole.name}</div>
     <div>所属光缆: ${this.cableMap[manhole.cableId]}</div>
     <div>位置: ${manhole.longitude.toFixed(6)}, ${manhole.latitude.toFixed(6)}</div>`,
    { title: "炮筒信息", width: 250 }
  );
  
  marker.addEventListener("click", () => {
    this.map.openInfoWindow(infoWindow, point);
  });
  
  this.map.addOverlay(marker);

  // 绘制连接的光缆（如果存在）
  const cableManholes = this.getSortedManholesByCableId(manhole.cableId);
  if (cableManholes.length > 1) {
    const points = cableManholes.map(m => new this.BMap.Point(m.longitude, m.latitude));
    const polyline = new this.BMap.Polyline(points, {
      strokeWeight: 6,
      strokeColor: '#FF0000',
      strokeOpacity: 0.7
    });
    this.map.addOverlay(polyline);
  }

  this.$message.success(`已高亮显示炮筒: ${manhole.name}`);
    },
    
    syncCenterAndZoom(e) {
      this.mapZoom = e.target.getZoom();
    },
    
    cancelAddCable() {
      this.showCableDialog = false;
      this.isAddingCable = false;
      this.cablePoints = [];
      this.clearMapOverlays();
      this.drawAllCables();
    },
    
    cancelAddManhole() {
      this.showManholeDialog = false;
      if (this.cablePoints.length > 0) {
        this.cablePoints.pop();
        this.clearMapOverlays();
        this.drawTempPolyline();
      }
    },
    resetHighlight() {
      this.searchKeyword = '';
      if (this.currentCompany) {
        this.showCurrentCompanyCables();
      } else {
        this.drawAllCables();
      }
    },
  }
};
</script>

<style scoped>
.map {
  width: 100%;
  height: calc(100vh - 60px);
  position: relative;
}

.map-controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.control-btn {
  margin: 5px 0;
  width: 100%;
}

.search-box {
  position: absolute;
  top: 10px;
  right: 50px;
  z-index: 1000;
  width: 350px;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-row {
  margin-bottom: 10px;
}

.el-col {
  display: flex;
  flex-direction: column;
}

.toggle-controls-btn {
  position: absolute;
  top: -15px;
  right: -15px;
  z-index: 1001;
  background: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.show-all-btn {
  margin-top: 10px;
  width: 100%;
}
</style>